class Solution:
    def minInsertions(self, s: str) -> int:
        stack = []
        i = 0
        res = 0
        while i < len(s):
            if s[i] == '(':
                stack.append(-1)
            elif i + 1 < len(s) and s[i + 1] == ')':
                if stack and stack[-1] == -1:
                    stack.pop()
                else:
                    stack.append(1)
                i += 1
            else:
                res += 1
                if stack and stack[-1] == -1:
                    stack.pop()
                else:
                    stack.append(1)
            i += 1
        while stack:
            i = stack.pop()
            if i == -1:
                res += 2
            else:
                res += 1
        return res
